package com.emm.yixun.website.controller.marketing;
//框架包
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.Retain;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.RetainDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.marketing.service.RetainServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.marketing.RetainService;
import com.emm.yixun.website.utils.ExcelUtil;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//website
//变化的引用
@Controller
@RequestMapping("/marketing/retain/")
public class RetainController extends BaseController<Retain> {

	@Autowired
	private RetainServiceFacade retainServiceFacade;
	@Autowired
	private RetainService retainService;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/marketing/retain/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "addRetainPage")
	public ModelAndView addRetainPage(Long roomId) {
		
		String userName = ShiroUtil.getCurrentUser().getUserName();
		return new ModelAndView("/marketing/retain/addRetain").addObject("roomId", roomId).addObject("userName",
				userName);
	}

	@RequestMapping(value = "retainDetail")
	public ModelAndView retainDetail(Long id,HttpServletRequest request,String returnUrl) {
		Response<Retain> retainResponse=retainServiceFacade.findById(id);
		String retainType="";
		if(retainResponse.isSuccess() && null!=retainResponse.getEntity()){
			retainType=retainResponse.getEntity().getRetainType();
		}
		return new ModelAndView("/marketing/retain/detail")
		.addObject("id", id)
		.addObject("permitBtn", getPermissionBtnArray())
		.addObject("menu", request.getParameter("menu"))
		.addObject("retainType", retainType)
		.addObject("returnUrl", returnUrl!=null&&!returnUrl.equals("")?returnUrl.replace(",", "/").replace("(", "?").replace(")", "="):"");
	}

	/**
	 * 	方法描述 :
	 *  保留详情 创建者：ThinkPad 
	 *  项目名称： emm-website 
	 *  类名： RetainController.java 
	 *  版本： v1.0 
	 *  创建时间： 2016年7月5日 下午8:33:27
	 * 
	 * @param id
	 * @return ExtResultVo
	 */
	@RequestMapping(value = "responseResult")
	public @ResponseBody
	ExtResultVo findRetain(Long id) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(retainServiceFacade.findRetainDetailById(id));
		return vo;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add")
	@ResponseBody
	public AjaxRes add(RetainDto dto, String starttime, String endTime) {
		AjaxRes ar = getAjaxRes();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:retain:add"))) {
			try {
				if (!StringUtils.isEmpty(starttime)) {
					dto.setStartValidity(df.parse(starttime));
				}
				if (!StringUtils.isEmpty(endTime)) {
					dto.setEndValidity(df.parse(endTime));
				}
				Response<RetainDto> response = retainServiceFacade.save(dto, ShiroUtil.getCurrentUser());
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:retain:view"))) {
			try {
				Response<Retain> response = retainServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(RetainDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:retain:edit"))) {
			try {
				Response<Integer> response = retainServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:retain:delete"))) {
			try {
				Response<Integer> response = retainServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Page<RetainDto> list(RetainDto dto, Integer limit, Integer page) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:retain:list")) {
			dto = setRetainDto(dto);
			Response<Page<RetainDto>> response = retainService.getRetainDtoList(dto, limit, page);
			if (response.isSuccess()) {
				Page<RetainDto> pages = response.getEntity();
				pages.setPageNumber(page);
				return pages;
			}
		}
		return new Page<RetainDto>();
	}
	
	public RetainDto setRetainDto(RetainDto dto){
		try {
			if(dto.getRetainDateAfter()!=null&&!dto.getRetainDateAfter().equals("")){
				dto.setRetainDateAfter(dto.getRetainDateAfter()+" 23:59:59");
			}
			if(dto.getEndValidityAfter()!=null&&!dto.getEndValidityAfter().equals("")){
				dto.setEndValidityAfter(dto.getEndValidityAfter()+" 23:59:59");
			}
			dto.setOrders(" t.create_time desc ");
			User user = ShiroUtil.getCurrentUser();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			
			//项目数据权限资源缓存
			String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
			if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
				dto.setResourcesCode(resourcesCode);
			}else if("".equals(resourcesCode)){
				ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return dto;
	}

	/**
	 * 方法描述 : 撤销保留 
	 * 创建者：ThinkPad 
	 * 项目名称： emm-website 
	 * 类名： RetainController.java 
	 * 版本： v1.0 
	 * 创建时间： 2016年7月6日 下午3:02:17
	 * 
	 * @param id
	 * @return AjaxRes
	 */
	@RequestMapping(value = "roomStatusRevoke")
	public @ResponseBody
	AjaxRes roomStatusRevoke(Long id, String remark) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		Response<Boolean> result = retainServiceFacade.roomStatusRevoke(id, user, remark);
		if (result.getEntity()) {
			ar.setSucceedMsg("撤销成功!");
		}
		return ar;
	}
	/**
	 * 
	 * retainExport:(保留导出). <br/>
	 * @author Administrator
	 * @param value
	 * @param response
	 * @param request
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "retainExport")
	public void retainExport(String value,HttpServletResponse response,HttpServletRequest request){

		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:retain:export"))){
				String jsonStr=URLDecoder.decode(value,"utf-8");
				RetainDto dto = JSONObject.parseObject(jsonStr, RetainDto.class);
				dto=setRetainDto(dto);
				String[] name = new String[]{"保留信息"}; //sheet信息
				List<String[]> headerList = new ArrayList<String[]>(); //表头集合
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
				//设置表头字段
				String[] header = new String[]{
					"保留日期","客户姓名","房号","户型","房屋总价","保留有效开始日期","保留有效结束日期","经纪人","业务状态"
				};
				headerList.add(header);
				List<RetainDto> retainList = retainService.queryRetainListExport(dto);
				List<Map<String, String>> listMap = returnFieldRetain(retainList, header);
				list.add(listMap);
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	public List<Map<String, String>> returnFieldRetain(List<RetainDto> list, String[] header) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		for (int i=0;i<list.size();i++) {
			RetainDto retainDto = list.get(i);
			HashMap<String, String> map = new HashMap<String, String>();
			map.put(header[0]+"_"+i, DateUtils.DateToString(retainDto.getRetainDate(), DateStyle.YYYY_MM_DD.getValue()));
			map.put(header[1]+"_"+i, retainDto.getCustomerName());
			map.put(header[2]+"_"+i,retainDto.getCombinedName());
			map.put(header[3]+"_"+i,retainDto.getHouseTypeName());
			map.put(header[4]+"_"+i,retainDto.getTotalPrice()==null?"":retainDto.getTotalPrice().toString());
			map.put(header[5]+"_"+i,DateUtils.DateToString(retainDto.getStartValidity(), DateStyle.YYYY_MM_DD.getValue()));
			map.put(header[6]+"_"+i,DateUtils.DateToString(retainDto.getEndValidity(), DateStyle.YYYY_MM_DD.getValue()));
			map.put(header[7]+"_"+i,retainDto.getUserName());
			if(!StringUtils.isEmpty(retainDto.getRetainType())){
				if(retainDto.getRetainType().equals("0")){
					map.put(header[8]+"_"+i,"保留");
				}else{
					map.put(header[8]+"_"+i,"解除保留");
				}
			}
			listMap.add(map);
		}
		return listMap;
	}
}
